<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Administrator;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Authentication\Adapter\DbTable as DbAuthAdapter;
use Zend\Authentication\AuthenticationService;
use Zend\Session\Container;
use Administrator\Model\User;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

use Zend\EventManager\EventInterface;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;

use Administrator\Model\ListUser;
use Administrator\Model\UserRole;
use Administrator\Model\PermissionTable;
use Administrator\Model\Resource;
use Administrator\Model\ResourceTable;
use Administrator\Model\RolePermissionTable;
use Administrator\Model\Role;
use Administrator\Utility\Acl;

class Module implements  AutoloaderProviderInterface,ConfigProviderInterface 
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);      
        $serviceManager = $e->getApplication()->getServiceManager();
        
       /**
     * Log any Uncaught Errors
     */
    $sharedManager = $eventManager->getSharedManager();
    $sharedManager->attach('Zend\Mvc\Application', 'dispatch.error',
         function($e) use ($serviceManager) {
            if ($e->getParam('exception')){
                $serviceManager->get('Zend\Log')->crit($e->getParam('exception'));
            }
         }
    );
        
        $eventManager->attach(MvcEvent::EVENT_DISPATCH, array(
        		$this,
        		'boforeDispatch'
        ), 100);
        /* $eventManager->attach(MvcEvent::EVENT_DISPATCH, array(
        		$this,
        		'afterDispatch'
        ), -100); */
       
    }
    
    function boforeDispatch(MvcEvent $event){
    	$request = $event->getRequest();
    	$response = $event->getResponse();
    	$target = $event->getTarget ();
    
    	/* Xác thực các module Ngoại tuyến không cần thiết
    	 * thuoc quyen quan ly cua module  Administrator*/
    	$whiteList = array (
    			'Administrator\Controller\Login-index',
    	);
    
    	/* Xác thực các module Ngoại tuyến không cần thiết
    	 * khong thuoc quyen quan ly cua module  Administrator*/
    	$whiteListApp = array (
    			'Application\Controller\Index-index',
    			'FrontEnd\Controller\Index-index',
    			'FrontEnd\Controller\Index-video',
    			'FrontEnd\Controller\Index-type',
    			'FrontEnd\Controller\Rss-feed'
    	);
    	
    	$requestUri = $request->getRequestUri();
    	$controller = $event->getRouteMatch ()->getParam ( 'controller' );
    	$action = $event->getRouteMatch ()->getParam ( 'action' );
        //$module = __NAMESPACE__;   	
    	
    	$requestedResourse = $controller . "-" . $action;

    	$session = new Container('User');
    
    	if ($session->offsetExists ( 'email' )) {
    		if ($requestedResourse == 'Administrator\Controller\Login-index' || in_array ( $requestedResourse, $whiteList )) {
    			$url = '/product/';
    			$response->setHeaders ( $response->getHeaders ()->addHeaderLine ( 'Location', $url ) );
    			$response->setStatusCode ( 302 );
    		} else {
                
                $serviceManager = $event->getApplication()->getServiceManager();
                $userRole = $session->offsetGet('roleName');
                
                $acl = $serviceManager->get('Acl');
                $acl->initAcl();
                
                $status = $acl->isAccessAllowed($userRole, $controller, $action);
                if (! $status && !in_array ( $requestedResourse, $whiteListApp )) {
                    die('<html><head><meta charset="utf-8">
                    		<link href="/public/template/css/font-awe/font-awesome.min.css" media="screen" rel="stylesheet" type="text/css">
                    		<link href="/public/template/css/bootstrap.min.css" media="screen" rel="stylesheet" type="text/css">
                    		</head><div class="alert alert-success" role="alert">
                    		<i class="fa fa-exclamation-circle"></i>                		
                    		Bạn không có quyền truy cập vào chức năng này !.
                    		Click vào <a href="/product/">đây</a> để quay về trang chủ</div></html>');
                }
            }
    	}else{
    
    		if ($requestedResourse != 'Administrator\Controller\Login-index' && ! in_array ( $requestedResourse, $whiteList ) && ! in_array ( $requestedResourse, $whiteListApp )) {
    			$url = '/system';
    			$response->setHeaders ( $response->getHeaders ()->addHeaderLine ( 'Location', $url ) );
    			$response->setStatusCode ( 302 );
    		}
    		$response->sendHeaders ();
    	}
    
    	//print "Called before any controller action called. Do any operation.";
    }
    
    function afterDispatch(MvcEvent $event){
    	//print "Called after any controller action called. Do any operation.";
    }
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
      
    // getAutoloaderConfig() and getConfig() methods here
    
    // Add this method:
    public function getServiceConfig()
    {
    	return array(

    			'factories' => array(
    					'Administrator\Model\UserTable' =>  function($sm) {
    						$tableGateway = $sm->get('SystemTableUser');
    						$table = new User($sm->get('Zend\Db\Adapter\Adapter'),$tableGateway);
    						return $table;
    					},
    					'SystemTableUser' => function ($sm) {
    						$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
    						$resultSetPrototype = new ResultSet();
    						$resultSetPrototype->setArrayObjectPrototype(new ListUser());
    						return new TableGateway('user', $dbAdapter, null, $resultSetPrototype);
    					},
    					'Administrator\Model\Resources' =>  function($sm) {
    						$tableGateway = $sm->get('SystemTableResources');
    						$table = new ResourceTable($sm->get('Zend\Db\Adapter\Adapter'),$tableGateway);
    						return $table;
    					},
    					'SystemTableResources' => function ($sm) {
    						$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
    						$resultSetPrototype = new ResultSet();
    						$resultSetPrototype->setArrayObjectPrototype(new Resource());
    						return new TableGateway('resource', $dbAdapter, null, $resultSetPrototype);
    					},
    					'AuthService' => function ($serviceManager) {
    						$adapter = $serviceManager->get('Zend\Db\Adapter\Adapter');
    						$dbAuthAdapter = new DbAuthAdapter ( $adapter, 'user', 'EMAIL_USER', 'PASS_USER');    						
    						$auth = new AuthenticationService();
    						$auth->setAdapter ( $dbAuthAdapter );
    						return $auth;
    					},
    					'AuthServiceActive' => function ($serviceManager) {
    						$adapter = $serviceManager->get('Zend\Db\Adapter\Adapter');
    						$dbAuthAdapter = new DbAuthAdapter ( $adapter, 'user', 'EMAIL_USER', 'PASS_USER','ACTIVE="1"');
    							
    						$select = $dbAuthAdapter->getDbSelect();
    						$select->where('ACTIVE = "1"');
    					
    						$auth = new AuthenticationService();
    						$auth->setAdapter ( $dbAuthAdapter );
    						return $auth;
    					},
    					'Acl' => function ($serviceManager)
    					{
    						return new Acl();
    					},
    					'UserTable' => function ($serviceManager)
    					{
    						return new User($serviceManager->get('Zend\Db\Adapter\Adapter'));
    					},
    					'RoleTable' => function ($serviceManager)
    					{
    						return new Role($serviceManager->get('Zend\Db\Adapter\Adapter'));
    					},
    					'UserRoleTable' => function ($serviceManager)
    					{
    						return new UserRole($serviceManager->get('Zend\Db\Adapter\Adapter'));
    					},
    					'PermissionTable' => function ($serviceManager)
    					{
    						return new PermissionTable($serviceManager->get('Zend\Db\Adapter\Adapter'));
    					},
    					'ResourceTable' => function ($serviceManager)
    					{
    						return new ResourceTable($serviceManager->get('Zend\Db\Adapter\Adapter'));
    					},
    					'RolePermissionTable' => function ($serviceManager)
    					{
    						return new RolePermissionTable($serviceManager->get('Zend\Db\Adapter\Adapter'));
    					}
    				
    			),
    			
    			
    	);
    }

}
